<template>
  <div class="login-box">
    <div class="login-container">
      <el-form label-width="70px" ref="form" :inline="true" :model="form" :rules="rules">
        <h3 class="login-title">在线考试系统</h3>
        <el-form-item label="用户名" prop="id">
          <el-input v-model="form.id" placeholder="请输入账号"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="form.password" placeholder="请输入密码" type="password"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button @click="submit" type="primary">登录</el-button>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>

<script>
import {login} from "@/api/student";
import {mapState, mapMutations} from 'vuex'
import {setToken} from "@/utils/auth";

export default {
  name: "Login",
  data() {
    return {
      form: {
        id: '200201418',
        password: '123456'
      },
      rules: {
        id: [
          {required: true, message: '请输入用户名', trigger: 'blur'},
          {min: 5, max: 18, message: '长度在 5 到 18 个字符', trigger: 'blur'}
        ],
        password: [
          {required: true, message: '请输入密码', trigger: 'blur'}
        ]
      }
    }
  },
  methods: {
    ...mapMutations(['loginUser']),
    submit() {

      this.$refs.form.validate((valid) => {
        if (valid) {
          login(this.form.id, this.form.password).then(res => {
            //将token存储为Cookie，并设置Cookie的超时时间为个小时
            setToken(res.token, 60 * 60 * 2)
            this.loginUser(res.user)
            this.$router.push({name: 'home'})
          })

        }
      })
    }
  }
}
</script>

<style scoped lang="less">
.login-box {
  width: 100%;
  height: calc(100vh - 180px);
  background-color: #3a8ee6;
  padding-top: 180px;


  .login-container {
    width: 350px;
    margin: 0px auto;
    border: 1px solid #eaeaea;
    padding: 35px 35px 15px 35px;
    background-color: #ffffff;
    border-radius: 15px;
    box-shadow: 0 0 25px #cac6c6;
    box-sizing: border-box;

    .login-title {
      text-align: center;
      font-size: 25px;
      color: #505458;
      margin-bottom: 40px;
    }

    .el-input {
      width: 198px;
    }

    .el-button {
      margin-left: 105px;
      margin-top: 10px;
    }
  }
}
</style>
